package com.kk.filter;


import com.alibaba.fastjson.JSON;
import com.kk.config.SpringContextBean;
import com.kk.util.redis.RedisUtils;
import com.kk.util.result.Result;
import lombok.extern.log4j.Log4j2;
import org.hibernate.annotations.common.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author: kevin
 * @data: 2018-08-31 14:31
 * @desc:   刚开始想用拦截器来实现token拦截的，但是拦截器在get请求的时候只能拦截到一次OPTIONS请求，而不能拦截到之后的get请求
 *        网上搜索了一下Filter能拦截到几乎所有请求，Interceptor只能拦截到部分(例如Action)请求，故最终选择Filter实现token无效的请求过滤
 */
@Log4j2
@Component
//@WebFilter(urlPatterns = { "/user/*" }, filterName = "tokenAuthFilter")
public class TokenAuthFilter implements Filter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtils redisUtils;
//    @Bean
//    public RedisUtils getRedisUtils() {
//        return new RedisUtils();
//    }
    @Override
    public void init(FilterConfig config) throws ServletException {
        if (redisTemplate == null && SpringContextBean.getBean("redisTemplate")!=null) {
            redisTemplate = SpringContextBean.getBean("redisTemplate");
        }
        if (redisUtils == null && SpringContextBean.getBean("redisUtils")!=null) {
            redisUtils = SpringContextBean.getBean("redisUtils");
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse rep = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        //设置允许跨域的配置
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Headers", "*");
//        rep.setHeader("Access-Control-Allow-Headers", "token, Origin, X-Requested-With, Content-Type, Accept, X-URL-PATH");


        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        String method = req.getMethod();
        if (method.equals("OPTIONS")) {
            log.info(method);
            rep.setStatus(HttpServletResponse.SC_OK);
        }else{
            String token = req.getHeader("token");
            boolean isFilter = false;
            if (StringHelper.isNotEmpty(token)) {
                if (redisTemplate != null) {
                    isFilter = redisTemplate.hasKey(token);
                }
                if (redisUtils != null) {
                    isFilter = redisUtils.exists(token);
                }
            }
            if (!isFilter) {
                PrintWriter pw = null;
                OutputStreamWriter osw = null;
                try {
                    osw = new OutputStreamWriter(response.getOutputStream(),
                            "UTF-8");
                    pw = new PrintWriter(osw, true);
                    String jsonStr = JSON.toJSONString(Result.error("403", "token无效"));
                    pw.write(jsonStr);
                    pw.flush();
                    pw.close();
                    osw.close();
                } catch (UnsupportedEncodingException e) {
                    log.error("过滤器返回信息失败:" + e.getMessage(), e);
                } catch (IOException e) {
                    log.error("过滤器返回信息失败:" + e.getMessage(), e);
                } finally {
                    if (null != pw) {
                        pw.close();
                    }
                    if (null != osw) {
                        osw.close();
                    }
                }
            } else {
                filterChain.doFilter(request, response);
            }
        }


    }

    @Override
    public void destroy() {

    }
}
